﻿
$(document).ready(function () {
    $(".groupselected li p").click(function () {
        $(this).addClass("node-selected");
        $(".groupselected li p").not(this).removeClass('node-selected');
    });

    $("#fr-searchpartviewstock").submit(function () {
        if (isNaN($("#partid").val())) {
            alert("Only numbers are allowed for PartID!");
            return false;
        }
        var serializedForm = $(this).serialize();
        App.blockUI($('.page-content'), false);
        $.ajax({
            type: 'POST',
            url: '/stockcontrol/searchpartviewstock',
            data: serializedForm,
            success: function (data) {
                $(".allpartviewstock").html(data);
                App.unblockUI($('.page-content'));
                InitDatatable();
                $(".tbl-selected tbody tr").click(function () {
                    $(this).addClass("row-selected");
                    $(".tbl-selected tbody tr").not(this).removeClass('row-selected');
                });
            },
            error: function () {
                alert('search fail!');
            }
        });
        return false;
    });

    $("#fr-editpartname").submit(function () {
        var serializedForm = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: '/stockcontrol/editpartname',
            data: serializedForm,
            success: function () {
                alert("Part Name Updated!");
            },
            error: function () {
                alert('Update false!');
            }
        });
        return false;
    });
    $("#tabviewbackorderedparts").click(function () {

        if (!$("#viewbackorderedparts").hasClass("IsLoaded")) {
            App.blockUI($("#viewbackorderedparts"));
            $.ajax({
                type: 'GET',
                url: '/stockcontrol/ViewBackOrderedParts',
                success: function (data) {
                    $("#viewbackorderedparts").addClass("IsLoaded");
                    $("#viewbackorderedparts").html(data);
                    LoadDataTable($('#viewbackorderedparts .krmtable'));
                    $("#viewbackorderedparts .krmtable tbody tr").click(function () {
                        $(this).addClass("row-selected");
                        $("#viewbackorderedparts .krmtable tbody tr").not(this).removeClass('row-selected');
                    });
                    App.unblockUI($("#viewbackorderedparts"));
                },
                error: function () {
                    alert('Load Faild');
                    App.unblockUI($("#viewbackorderedparts"));
                }
            });
        }
    });
    $(".vehicle-item").click(function () {
        $.ajax({
            url: "/stockcontrol/getvehicledetail?id=" + $(this).val(),
            success: function (data) {
                $(".vehicledetail").html(data);
            }
        });
    });


    $("#fr-editpart").submit(function () {
        App.blockUI($('body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: '/stockcontrol/SavePartWithMewVesion',
            data: serializedForm,
            success: function (data) {
                if (data == "1") {
                    if (confirm("Margin set to BELOW MINIMUM - this is CONTRAVENTION of COMPANY POLICY!!!")) {
                        if ($("#hfversion").val() != $("#tbversion").val()) {
                            $("#partVersionChangeLog").modal("show");
                            $("#fr-partVersionChangeLog").submit(function () {
                                var serializedFormChangeLog = $(this).serialize();

                                $.ajax({
                                    type: 'POST',
                                    url: '/stockcontrol/partVersionChangeLog',
                                    data: serializedFormChangeLog,
                                    success: function () {
                                        $("#partVersionChangeLog").modal("hide");
                                        $.ajax({
                                            type: 'POST',
                                            url: '/stockcontrol/editpart',
                                            data: serializedForm,
                                            success: function (mes) {
                                                alert(mes.mes);
                                                window.location = "/stockcontrol/editpart?partid=" + mes.partid;
                                                App.unblockUI($('body'));
                                            }
                                        });
                                        return false;
                                    },
                                    error: function () {
                                        alert('Fail!');
                                        App.unblockUI($('body'));
                                    }
                                });
                                return false;
                            });
                        } else {
                            $.ajax({
                                type: 'POST',
                                url: '/stockcontrol/editpart',
                                data: serializedForm,
                                success: function (mes) {
                                    alert(mes.mes);
                                    window.location = "/stockcontrol/editpart?partid=" + mes.partid;
                                    App.unblockUI($('body'));
                                }
                            });
                            return false;
                        }
                    }
                } else if (data == "2") {
                    $.ajax({
                        type: 'POST',
                        url: '/stockcontrol/editpart',
                        data: serializedForm,
                        success: function (mes) {
                            alert(mes.mes);
                            window.location = "/stockcontrol/editpart?partid=" + mes.partid;
                            App.unblockUI($('body'));
                        }
                    });
                    return false;
                } else {
                    alert(data);
                    App.unblockUI($('body'));
                    return false;
                }
            },
            error: function () {
                alert('Update false, please reload this page!');
                App.unblockUI($('body'));
            }
        });
        return false;
    });

    $("#fr-addstock").submit(function () {
        if (isNaN($("#qty").val())) {
            alert("Only numbers are allowed for Quantity!");
            return false;
        }
        App.blockUI($('body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/GetShippingPriority',
            data: serializedForm,
            success: function (data) {
                if (data == 0) {
                    if (confirm("This warehouse does not have a shipping priority set - \r\n Do you still want to add stock?")) {
                        $.ajax({
                            url: '/stockcontrol/StockControl',
                            type: 'POST',
                            data: serializedForm,
                            success: function (data) {
                                alert(data.message);
                                window.location = "/stockcontrol/stockcontroladmin?partid=" + data.partid;
                            }
                        });
                    }
                } else {
                    $.ajax({
                        url: '/stockcontrol/StockControl',
                        type: 'POST',
                        data: serializedForm,
                        success: function (data) {
                            alert(data.message);
                            window.location = "/stockcontrol/stockcontroladmin?partid=" + data.partid;
                        }
                    });
                }
            }
        });
        return false;
    });
    $("#fr-reducestock").submit(function () {
        if (isNaN($("#qtyreduce").val())) {
            alert("Only numbers are allowed for Quantity!");
            return false;
        }
        App.blockUI($('body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/ReduceStock',
            data: serializedForm,
            type: 'POST',
            success: function (data) {
                if (data.success == 1) {
                    alert(data.message);
                    window.location = "/stockcontrol/stockcontroladmin?partid=" + data.partid;
                } else {
                    alert(data.message);
                    App.unblockUI($('body'));
                }
            }, error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        return false;
    });

    $("#fr-transferstock").submit(function () {
        if (isNaN($("#qtytransfer").val())) {
            alert("Only numbers are allowed for Quantity!");
            return false;
        }
        App.blockUI($('body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/transferstock',
            data: serializedForm,
            type: 'POST',
            success: function (data) {
                if (data.success == 1) {
                    alert(data.Message);
                    window.location = "/stockcontrol/stockcontroladmin?partid=" + data.partid;
                } else {
                    alert(data.message);
                    App.unblockUI($('body'));
                }
            }, error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        return false;
    });

    $("#fr-shippingpriority").submit(function () {
        if (isNaN($("#reorder").val())) {
            alert("Only numbers are allowed for ReOrder!");
            return false;
        }
        App.blockUI($('body'), false);
        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/shippingpriority',
            data: serializedForm + "&reorder=" + $("#reorder").val(),
            type: 'POST',
            success: function (data) {
                if (data.success == 1) {
                    alert(data.message);
                    window.location = "/stockcontrol/stockcontroladmin?partid=" + data.partid;
                } else {
                    alert(data.message);
                    App.unblockUI($('body'));
                }
            }, error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        return false;
    });


    $('#fr-SearchPostcode').submit(function () {
        if ($('#btn-SearchPostcode').attr("type").valueOf() == "submit") {
            $('#btn-SearchPostcode').attr("type", "button");
            LoadPostcodeAlert('0');
        }

        return false;
    });
    $('#fr-shiping').submit(function () {
        App.blockUI($('body'), false);

        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/AmendAddressOn',
            data: serializedForm,
            type: 'POST',
            success: function (data) {
                if (data.success == 1) {
                    document.getElementsByName("newShipAdd")[0].value = data.NewShipAdd;
                    $('#fr-billing').submit();
                } else {
                    alert(data.message);
                    App.unblockUI($('body'));
                }
            }, error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        return false;
    });

    $('#fr-billing').submit(function () {

        var serializedForm = $(this).serialize();
        $.ajax({
            url: '/stockcontrol/AmendAddressOn?newShipAdd=' + document.getElementsByName("newShipAdd")[0].value,
            data: serializedForm,
            type: 'POST',
            success: function (data) {
                if (data.success == 1) {

                    if (confirm("Do you want to recheck this order now")) {
                        $.ajax({
                            url: '/stockcontrol/RecheckThisOrder?OrderID=' + data.OrderID + '&Orderref=' + data.Orderref,
                            type: 'POST',
                            success: function (data1) {
                                alert(data1.message);
                                window.close();
                                window.opener.submitpostcode();
                            }, error: function () {
                                alert("Error");
                                window.close();
                            }
                        });
                    } else {
                        window.opener.submitpostcode();
                    }
                } else {
                    alert(data.message);
                    App.unblockUI($('body'));
                }
            }, error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        return false;
    });

    $('#fr-SetExtraDeliveryCost').submit(function () {
        App.blockUI($('body'));
        $.ajax({
            url: "/stockcontrol/SetExtraDeliveryCost",
            data: $(this).serialize(),
            type: "POST",
            success: function (data) {
                if (data.success == 1) {
                    if (confirm(data.message)) {
                        $.ajax({
                            url: "/stockcontrol/ConfirmSendMail?orderRef=" + data.OrderRef + "&orderID=" + data.OrderID + "&nbCost=" + data.NbCost,
                            success: function (data1) {
                                window.opener.submitpostcode();
                                alert(data1.message);
                                window.close();
                            }, error: function () {
                                alert("Error");
                                App.unblockUI($('body'));
                            }
                        });
                    }
                } else {
                    alert(data.message);
                }
            }
            ,
            error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });
        App.unblockUI($('body'));
        return false;
    });
    $('#fr-postcode').submit(function () {
        App.blockUI($('body'));
        $.ajax({
            url: "/stockcontrol/LoadHeldOrder",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
                $('#loadheldorder').html(data);
                App.unblockUI($('body'));
            },
            error: function () {
                alert("Error");
                App.unblockUI($('body'));
            }
        });

        return false;
    });

});

function AddToGroupFilter() {
    $(".groupselected li .node-selected").each(function () {
        var data = "";
        $(this).parent().find("p").each(function () {
            data += "<input name='groupFilter' type='hidden' value='" + $(this).data('id') + "'/>";
        });
        $("#groupedFilter").append("<li>" + data + "<p>" + $(this).html() + "</p></li>");
        $("#groupedFilter li").click(function () {
            $(this).addClass("node-selected");
            $("#groupedFilter li").not(this).removeClass('node-selected');
        });
    });
}
function removeGroupedFilter() {
    $("#groupedFilter .node-selected").each(function () {
        $(this).remove();
    });
}

function partitemselected(partid) {
    $(".btn-addorderstock").attr("onclick", "PopupCenter('/stockcontrol/addorderstock?partid=" + partid + "',800,500)");
    $(".btn-stockcontrol").attr("onclick", "PopupCenter('/stockcontrol/stockcontroladmin?partid=" + partid + "',800,600)");
    $(".btn-viewpart").attr("onclick", "PopupCenter('/stockcontrol/editpart?partid=" + partid + "',900,650)");
}

function vatchange(combo, singular) {
    if (singular == 'true') {
        $("#singleIndivCharge").attr("readonly", "readonly");
        $("#cbsingular").removeAttr("disabled");
    } else {
        $("#cbsingular").attr("disabled", "disabled");
        $("#singleIndivCharge").removeAttr("readonly");
    }
    var vatcheck = $("#cbvat").is(":checked");
    if (vatcheck) {
        $("#incVAT").val("0");
        $("#incVAT").removeAttr("readonly");
    } else {
        $("#incVAT").attr("readonly", "readonly");
    }
    var outtrade = $("#outtrade").val();
    var retailincvat = $("#RetailIncVAT").val();
    var partid = $("#hfpartid").val();
    var incVAT = $("#incVAT").val();
    var singleIndivCharge = $("#singleIndivCharge").val();
    App.blockUI($('.padding10'), false);
    $.ajax({
        url: "/stockcontrol/vatchange",
        data: {
            partid: partid, vatcheck: vatcheck, outtrade: outtrade, retailincvat: retailincvat,
            incVAT: incVAT, combo: combo, singular: singular, singleIndivCharge: singleIndivCharge
        },
        success: function (data) {
            $("#incVAT").val(data.incVAT);
            $("#OurTradeIncCarriage").val(data.OurTradeIncCarriage);
            $("#RetailExcVAT").val(data.RetailExcVAT);
            $(".ProfitPounds").html(data.ProfitPounds);
            $(".ProfitPercent").html(data.ProfitPercent);
            $("#Carriage").val(data.Carriage);
            $("#TradeWithDiscount").val(data.TradeWithDiscount);
            $(".ProfPoundsWithDis").html(data.ProfPoundsWithDis);
            $(".ProfPercWithDis").html(data.ProfPercWithDis);
            App.unblockUI($('.padding10'));
        }
    });
}

function loadwaitingitems(orderref) {
    App.blockUI($('#itemwaitingresult'));
    $.ajax({
        url: "/stockcontrol/LoadBackWaitingItems",
        type: "GET",
        data: { orderref: orderref },
        success: function (data) {
            $('#itemwaitingresult').html(data);
            LoadDataTable($('#itemwaitingresult .krmtable'));
            App.unblockUI($('#itemwaitingresult'));
        }
    });
}
function selectdpartgroupid() {
    var id = $(".group-filter-tree-bg").find("p.node-selected").attr("data-id");
    if (id != undefined) {
        $.ajax({
            url: "/stockcontrol/getpartgrouplink?groupid=" + id,
            success: function (data) {
                $(".partgrouplink").html(data);
                $("#hfpartgroupid").val(id);
            }
        });
    }
    $("#partGroup").modal("hide");
}

function loadhelditems(orderref) {
    App.blockUI($('#itemheldresult'));
    $.ajax({
        url: "/stockcontrol/LoadBackHeldItems",
        type: "GET",
        data: { orderref: orderref },
        success: function (data) {
            $('#itemheldresult').html(data);
            LoadDataTable($('#itemheldresult .krmtable'));
            $("#itemheldresult .krmtable tbody tr").click(function () {
                $(this).addClass("row-selected");
                $("#itemheldresult .krmtable tbody tr").not(this).removeClass('row-selected');
            });
            App.unblockUI($('#itemheldresult'));
        }
    });
}
function selectedheldorder(orderref) {
    var row = $('tr[data-orderref="' + orderref + '"]:first');
    if (row.length > 0) {
        row.click();
        $('#tb-heldorder').parent().animate({
            scrollTop: row.offset().top - $('#tb-heldorder').offset().top - 35
        }, 1000);
    } else {
        alert("Order Ref not found");
    }
}
function selectdvehicleid() {
    var id = "";
    $(".lstvehicles input").each(function (index) {
        if ($(this).is(":checked")) {
            id += "," + $(this).val();
        }
    });
    $.ajax({
        url: "/stockcontrol/getvehiclename?id=" + id,
        success: function (data) {
            $(".VehiclesLink").html(data.name);
            $("#hfvehicleid").val(data.id);
        }
    });
    $("#SelectVehicles").modal("hide");
}

function carrierservicechange(combo, partid) {
    $.ajax({
        url: "/stockcontrol/carrierservicechange",
        data: { serviceid: combo.val(), partid: partid },
        success: function (data) {
            combo.find($("option").val() == '0').remove();
            combo.prepend("<option value='0'></option>");
            combo.val(data.id);
            if (data.mes != "") {
                alert(data.mes);
            }
        }
    });
}

function checkpermissionsend(sentStockId, orderref) {
    App.blockUI($('#itemheldresult'));
    $.ajax({
        url: "/stockcontrol/HasPermissionSend",
        type: "GET",
        success: function (data) {
            if (data == "True") {
                $("#btn-senditems").removeAttr("disabled");
            } else {
                $("#btn-senditems").attr("disabled", "disabled");
            }
            $("#btn-senditems").attr("onclick", "sendhelditems(" + sentStockId + ",'" + orderref + "')");
            App.unblockUI($('#itemheldresult'));
        }
    });
}
function sendhelditems(sentStockId, orderref) {
    App.blockUI($('#itemheldresult'));
    $.ajax({
        url: "/stockcontrol/SendHeldItems",
        type: "GET",
        data: { sentStockId: sentStockId },
        success: function (data) {
            loadhelditems(orderref);
        }
    });
}
function loadorderwaitingforpart(partid) {
    App.blockUI($('#orderwaitingforpartresult'));
    $.ajax({
        url: "/stockcontrol/LoadOrderWaitingForParts",
        type: "GET",
        data: { partid: partid },
        success: function (data) {
            $('#orderwaitingforpartresult').html(data);
            LoadDataTable($('#orderwaitingforpartresult .krmtable'));
            $("#orderwaitingforpartresult .krmtable tbody tr").click(function () {
                $(this).addClass("row-selected");
                $("#orderwaitingforpartresult .krmtable tbody tr").not(this).removeClass('row-selected');
            });
            App.unblockUI($('#orderwaitingforpartresult'));
        }
    });

}
function loadorderwaitingforpartaction(partid, orderref, warehouseid) {
    App.blockUI($('#orderwaitingforpartresult'));
    $.ajax({
        url: "/stockcontrol/LoadOrderWaitingForPartsAction",
        type: "GET",
        data: { partid: partid, orderref: orderref, warehouseid: warehouseid },
        success: function (data) {
            $('#orderwaitingforpart-action').html(data);
            App.unblockUI($('#orderwaitingforpartresult'));
        }
    });
}

function LoadPostcodeAlert(charCode) {

    if (charCode == '0') {
        charCode = $('#SearchPostcode').val();
    }
    $('#SearchPostcode').val(charCode);
    $('#postcode-item').html('');
    $.ajax({
        url: "/StockControl/LoadPostcodeAlerts?charCode=" + charCode,
        success: function (data) {
            App.blockUIMess($('#postcodealert'), false, "Loading Postcode: " + data.Outcodes.length + '/' + data.Outcodes.length + ' items');
            LoadPostcodeAlertItem(data, 0, data.CharCode);
        },
        error: function () {
            App.unblockUI($('#postcodealert'));
        }
    });
}

function LoadPostcodeAlertItem(data, i, charCode) {
    $('#block-mess span').html('Loading Postcode: ' + (i) + '/' + data.Outcodes.length + ' items');
    $.ajax({
        url: "/StockControl/LoadPostcodeAlertItem?CharCode=" + data.CharCode + "&outCode=" + data.Outcodes[i],
        success: function (data1) {
            $('#postcode-item').append(data1);
            if (i == data.Outcodes.length - 1) {
                App.unblockUI($('#postcodealert'));
                $('#btn-SearchPostcode').attr("type", "submit");
                $('#btn-saveallpostcode').attr("onclick", "SaveAllPostCode()");
            }
            if ((i + 1) < data.Outcodes.length) {
                LoadPostcodeAlertItem(data, i + 1, charCode);
            }
        },
        error: function () {
            App.unblockUI($('#postcodealert'));
        }
    });
}

function SaveAllPostCode() {
    App.blockUIMess($('#postcodealert'), false, "Saving Postcode: 0 items");
    var charCode = $('#SearchPostcode').val();
    $.ajax({
        url: "/StockControl/SaveAllPostCode?charCode=" + charCode,
        success: function (data) {
            SavePostcodeAlertItem(data, 0);
        },
        error: function () {
            App.unblockUI($('#postcodealert'));
        }
    });

}
function SavePostcodeAlertItem(data, i) {
    $('#block-mess span').html('Saving Postcode: ' + (i) + '/' + data.Outcodes.length + ' items');
    if (i == data.Outcodes.length - 1) {
        App.unblockUI($('#postcodealert'));
    }
    $.ajax({
        url: "/StockControl/SavePostcodeAlertItem",
        data: $('#fr-postcodeitem-' + data.Outcodes[i]).serialize(),
        success: function () {
            if ((i + 1) < data.Outcodes.length) {
                SavePostcodeAlertItem(data, i + 1);
            }
        }
    });
}
function SetExtraDeliveryCost(setExtraDeliveryCost, orderID, postcode, orderItemID) {
    if (setExtraDeliveryCost == "Set Extra Delivery Cost") {
        var url = "/stockcontrol/SetExtraDeliveryCost?&orderID=" + orderID + "&Postcode=" + postcode + "&OrderItemID=" + orderItemID;
        PopupCenter(url, 400, 300);
    } else if (setExtraDeliveryCost.indexOf("Take extra payment of ") != -1) {
        if (confirm("Are you sure extra payment of " + setExtraDeliveryCost.replace("Take extra payment of ", "") + " has been taken?")) {
            App.blockUI($('body'));
            $.ajax({
                url: "/StockControl/ExtraPayment?orderID=" + orderID,
                success: function (data) {
                    alert(data.message);
                    submitpostcode();

                }, error: function () {
                    alert("Error");
                    App.unblockUI($('body'));
                }
            });
        }
    }
}

function ReleaseItem(orderItemID, orderRef, productName) {
    App.blockUI($('body'));
    $.ajax({
        url: "/StockControl/ReleaseItem?orderItemID=" + orderItemID + "&orderRef=" + orderRef + "&productName=" + productName,
        success: function (data) {
            alert(data.message);
            submitpostcode();

        }, error: function () {
            alert("Error");
            App.unblockUI($('body'));
        }
    });
}
function MarkedOrderToFix(orderID) {
    App.blockUI($('body'));
    $.ajax({
        url: "/StockControl/MarkedOrderToFix?orderID=" + orderID,
        success: function (data) {
            alert(data.message);
            submitpostcode();
        }, error: function () {
            alert("Error");
            App.unblockUI($('body'));
        }
    });
}

function submitpostcode() {
    $('#fr-postcode').submit();

}

function HeldOrderSelected(id) {
    document.getElementsByName("helditemselected")[0].value = id;
}